<?php

/**
 * Rooms View for RoomBooking Component
 * 
 * @package    Joomla.RoomBooking
 * @subpackage Components
 * @license        GNU/GPL
 */
// No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.view');

class RoomBookingViewCsv extends JView {

    /**
     * Rooms view display method
     * @return void
     * */
    function display($tpl = null) {
        // Get data from the model
        $model = &$this->getModel('bookings');
        $items = & $model->getInfoCsv();
        $user = & JFactory::getUser();
        $name = $user->get('name');
        $year = JRequest::getVar('year');
        if ($year == null || $year == 0)
            $year = 'すべての年';
        $month = JRequest::getVar('month');
        if ($month == null || $month == 0)
            $month = 'すべての月';
        else
            $month = '0' . (int) $month;
        $now_month = (int) date('m');
        $this->csv('CSY-RVR-GWK52M78,' . $year . ',' . $month . ',' . date('Y') . ',' . $now_month . ',' . date('d') . ',' . date('H') . ',' . date('i') . ',' . date('s') . ',' . $name);

        $total = 0;
        $cur_username = '';
        for ($i = 0, $n = count($items); $i < $n; $i++) {
            $row = & $items[$i];
            if ($cur_username == '') {
                $total += $row->cost + $row->charge;
                $cur_username = $row->username;
            } else if ($row->username != $cur_username) {
                $this->csv($row->username . ',' . $row->name . ',' . $total . ',' . $row->address . ',' . $row->phone);
                $cur_username = $row->username;
                $total = $row->cost + $row->charge;
            }else{
                $total += $row->cost + $row->charge;
            }
//            $total = $row->cost + $row->charge;
//            $room = 'Room '.$row->room_name.' '.$row->floor.' floor '.$row->building_name.' '.$row->address;
        }
        $this->csv($row->username . ',' . $row->name . ',' . $total . ',' . $row->address . ',' . $row->phone);

        $end = 'END___END___END,' . $year . ',' . $month;
        $this->csv($end);

        $this->addTemplatePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'views' . DS . 'statistics' . DS . 'tmpl');
        $this->assignRef('items', $items);

        parent::display($tpl);
    }

    function csv($con) {
        jimport('joomla.error.log');
        // Define the file name as a PHP constant
        define('ROOM_BOOKING_CSV', 'booking.csv.' . date('Y_m_d_H_i_s') . '.csv');

        $log = &JLog::getInstance(ROOM_BOOKING_CSV, null, '../csv');

        // Just adding a comment
        $log->addLine($con);
    }

}
